/*
 * This file is part of ddesktop: remote desktop system for iPad 
 *
 * Copyright (C) 2010 Kazuhiro Satoh
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, see <http://www.gnu.org/licenses/>.
 */


#pragma once
#pragma unmanaged

#include "stdafx.h"
#include "DesktopCapture.h"
#include "AbstractEncoder.h"
#include "../../include/constants.h"

#include <windows.h>
#include <winsock.h>


namespace DDesktopServer {


	class IDDServerPortCommandDelegator{
	public:
		virtual bool DDServerPortChangeState(void) = 0;
		virtual bool DDServerPortCommandSendImageHeader(
			int image_width, int image_height, int image_scale, const unsigned char **header_buf, int* header_length) = 0;
		virtual bool DDServerPortCommandUIEvent(DDUIEventType type, DDUIEventOwner owner, int param1, int param2) = 0;
		virtual bool DDServerPortCommandKeyinputs(char* buf, int len) = 0;
		virtual bool DDServerPortCommandSetDownloadFrame(int x, int y, int width, int height, int zoom_scale) = 0;
		virtual bool DDServerPortCommandDownloadFrame(int x, int y, int width, int height, char **result_buf, DWORD* result_len) = 0;
		virtual bool DDServerPortCommandChangeImageQuality(int quality) = 0;
		virtual bool DDServerPortCommandChangeImageResolution(int resolution) = 0;
	};


	class DDServerPort
	{
	private:
		IDDServerPortCommandDelegator* m_command_delegator;
		struct sockaddr_in m_client_addr;
		char m_client_addr_str[64];
		int m_send_data_port;
		int m_receive_command_port;
		bool m_terminate_receive_thread;
		SOCKET m_send_data_socket;
		bool m_send_data_socket_is_opened;
		bool m_is_connected;

		HANDLE m_receive_command_thread_handle;

		bool OpenSendDataSocket(void);
		bool CloseSendDataSocket(void);

		static DWORD WINAPI ReceiveCommandThreadProc(LPVOID _self);

	public:

		DDServerPort(void);
		~DDServerPort();

		bool Init(int command_port, IDDServerPortCommandDelegator* delegator);
		bool Close(void);

		bool SendData(const unsigned char* buf, int length, int x, int y, int width, int height, int zoom_scale);

		// get state
		bool SendDataSocketIsOpened(void) const;
		bool IsConnected(void) const;
		const char* GetClientAddr(void) const;
		int GetDataPort(void) const;
	};
}


#pragma managed

